#!/usr/bin/perl
# SCRIPT PAGE
use strict;
use warnings;
require 'forum_common.pl';

connect_to_database() or bad_deal();
my $user = get_current_user(get_sess_id());

record_this_hit();

my $topic_id = url_param('id');
bad_deal('No topic specified!') unless (defined $topic_id);


my ($topic, $post);
bad_deal() unless ($topic = get_topic($topic_id) and
					$post = get_post($topic->{FIRST_POST}) and
					!($forum::errmsg = cant_edittopic($user, $topic)));
my $topic_title = escapeHTML($topic->{TITLE});
my $board_title = escapeHTML($topic->{B_TITLE});

my ($msg, $title, $descr, $content) = ('');
if (defined($title = param('title')) &&
	defined($descr = param('descr')) &&
	defined($content = param('content')) &&
	$ENV{'REQUEST_METHOD'} eq 'POST')
{
	my $submit;
	if (defined($submit = param('submit')) && $submit eq $forum::preview_text)
	{
		$msg = forum_error('',join(br(),verify_topic($title,$descr,$content)));
		$msg .= div({-id=>'post_preview'}, as_post($content));
	}
	elsif (edit_topic($topic, $user, $title, $descr, $content))
	{
		print redirect(-status=>303, -location=>"topic.cgi?id=$topic_id");
		exit;
	}
	else
	{
		$msg = nl2br(forum_error());
	}
}

print
	header($forum::http_header), forum_start(forum_cpanel($user)),
	"Board: $board_title", br(),
	br(),
	$msg,
	start_form(-action=>'', -method=>'post'),
	'<fieldset id="maketopic">',
	legend('New Topic'),
	'Title: (max 64 characters)', br(),
	textfield(-name=>'title', -size=>32, -maxlength=>64,
				-value=>($title || $topic->{TITLE})), br(),
	'Description: (max 128 characters)', br(),
	textfield(-name=>'descr', -size=>64, -maxlength=>128,
				-value=>($descr || $topic->{DESCR})), br(),
	'Post Content: (max 15000 characters)', br(),
	textarea(-name=>'content', -cols=>100, -rows=>20, -id=>'postcontent',
				-value=>($content || $post->{CONTENT})),
	div({-class=>'subbtn'},
		submit(-name=>'submit', -value=>'Preview'),
		submit(-name=>'submit', -value=>'Edit Topic')),
	'</fieldset>',
	end_form();


gameover:
print forum_end();
forum_disconnect();
